from django.shortcuts import redirect,render,HttpResponse
from django import forms

from app02 import models
from app02.utils.encrypt import md5
from app02.utils.code import check_code
from app02.utils.bootrsap import BootrsapForm


class LoginForm(BootrsapForm):
    user_n=forms.CharField(
        label='用户名',
        widget=forms.TextInput(attrs={'class':'form-control'}),
        required=True  #必须填写 不能为空
        )
    password=forms.CharField(
        label="密码",
        widget=forms.PasswordInput( attrs={'class': 'form-control'}),
        required=True
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )
    def clean_password(self):
        pwd =self.cleaned_data.get('password')
        return md5(pwd)
def login(request):
    # 登录
    if request.method=='GET':
        form = LoginForm()
        return render( request, 'account_dl.html', {"form": form} )
    form =LoginForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # form.cleaned_data={'username': 'tbfaj864', 'password': 'cb68dabb852f388164f69156295dd297',code:xxxx}

        #验证码的校验
        # 把验证码从数组删除并返回code
        user_input_code=form.cleaned_data.pop('code')
        # 获取到用户输入的验证码
        codes=request.session.get('image_code')
        # 当用户输入的验证码不等于生成的验证码返回错误提示
        if user_input_code.upper() != codes.upper():
            form.add_error( 'code', '验证码错误' )
            return render( request, 'account_dl.html', {"form": form} )

        # 获取到的数据去到数据库中校验
        admin_object=models.Admins.objects.filter(**form.cleaned_data).first()
        # 当获取的数据为none时
        if not admin_object:
            form.add_error('password','用户名或密码错误')
            return render( request, 'account_dl.html', {"form": form} )
        #用户名跟密码正确
        request.session['info']={"id":admin_object.id,"name":admin_object.user_n}
        # session可以保存7天
        request.session.set_expiry( 60 * 60 * 24 * 7)
        return redirect('/depart/list/')
    return render( request, 'account_dl.html', {"form": form} )

from io import BytesIO
def image_code(request):
   """生成验证码图片"""

   # 调用pillow函数，生成图片
   img,code_string=check_code()
   print(code_string)
   # 写入到session中(以便后面获取验证码进行校验)
   request.session['image_code']=code_string
   #给session设置超时60s
   request.session.set_expiry(60)

   stream = BytesIO()
   img.save(stream,'png')
   return HttpResponse(stream.getvalue())

def logout(request):
    # 注销
    request.session.clear()
    return redirect('/login/dl/')